package online.afeibaili.storebackendframework.config.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import online.afeibaili.storebackendframework.server.AdminInfoServer;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AdminInterceptor implements HandlerInterceptor {
    private final AdminInfoServer adminInfoServer;

    public AdminInterceptor(AdminInfoServer adminInfoServer) {
        this.adminInfoServer = adminInfoServer;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if (adminInfoServer.selectByToken(token) != null) {
            return true;
        }
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().write("{\"code\":403, \"message\":\"Unauthorized access\"}");
        return false;
    }
}
